package com.imy.lua.manger.callback;

import android.os.ConditionVariable;
import android.util.Log;

import com.immomo.mls.utils.LVCallback;
import com.immomo.mls.wrapper.callback.BaseCallback;
import com.immomo.mls.wrapper.callback.DefaultBoolCallback;
import com.immomo.mls.wrapper.callback.IBoolCallback;
import com.immomo.mls.wrapper.callback.IIntCallback;
import com.immomo.mls.wrapper.callback.IStringCallback;
import com.imy.common.util.ALog;
import com.imy.lua.manger.thread.ThreadManger;

import java.util.HashMap;

/**
 * Script callBack 脚本回调
 */
public class CallBackManger {

  private static volatile CallBackManger manger = new CallBackManger();
  private HashMap<String, Object> mCache = new HashMap<>();

  public void addCache(String tag, Object callback) {
    mCache.put(tag, callback);
  }

  public static final String WATCH = "watch";
  public static final String WINDOWS = "windows";
  public static final String KEY_EVENT = "key_event";

  public static CallBackManger get() {
    return manger;
  }

  public void call(String tag, boolean callClear, Object... objects) {
    call(tag, objects);
    if (callClear) {
      mCache.remove(tag);
    }
  }


    /**
     * 回调切换到主线程
     * @param tag
     * @param objects
     * @return
     */
  public Object call(String tag, Object... objects) {
    ConditionVariable callLock = new ConditionVariable();
      final Object[] call = { null };
      if (ThreadManger.setUserScriptThread){
        ThreadManger.getScriptThread().execute(new Runnable() {
          @Override
          public void run() {
            try {
              call[0] = startCall(tag, objects);
            } catch (Exception e) {
              ALog.e("Function error :" + e.getMessage());
            }finally {
              callLock.open();
            }
          }
        });
        callLock.block();
        return call[0];
      }else {
        return startCall(tag,objects);
      }

  }

  private Object startCall(String tag, Object... objects) {
    Object o = mCache.get(tag);
    if (o instanceof LVCallback) {
      LVCallback callback = (LVCallback) o;
      return callback.call(objects);
    } else if (o instanceof IBoolCallback) {
      IBoolCallback callback = (IBoolCallback) o;
     return callback.callback(objects);
    } else if (o instanceof IStringCallback) {
      IStringCallback callback = (IStringCallback) o;
      return callback.callback(objects);
    } else if (o instanceof IIntCallback) {
      IIntCallback callback = (IIntCallback) o;
     return callback.callback(objects);
    }
    return null;
  }

  public void clear() {
    mCache.clear();
  }
}